<?php

namespace App\Store\Controllers\Order;

use App\Store\Services\Financial;
use App\Store\Services\Member\CommonMember;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Member\MemberBalanceChangelog;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Member\Member;

use App\Common\Services\CommonExcelExport;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Goods\GoodsGlodprice;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsLog;
use App\Store\Models\Goods\GoodsSend\GoodsSendgoodsStock;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Models\Member\MemberPointsChangelog;
use App\Store\Models\Member\SiteMemberLv;
use App\Store\Models\OldMaterial\Stock;
use App\Store\Models\Order\OrderCommissionLog;
use App\Store\Models\Order\OrderSales;
use App\Store\Models\Order\OrderSalesGoods;
use App\Store\Models\Order\OrderSalesRecoveryGoods;
use App\Store\Models\Order\OrderSalesRedflush;
use App\Store\Models\Order\OrderSalesSendGoods;
use App\Store\Models\Wxapp\WxappCouponCodeList;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Goods\Goods;
use Illuminate\Support\Facades\DB;

/**
 * 红冲订单列表
 */
class OrderSalesRedflushController extends Controller
{

    /**
     * 列表
     */
    public function getorderlist(Request $request)
    {
        $list = OrderSalesRedflush::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 订单详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderSalesRedflush::with(['memberinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'storeinfo', 'orderinfo', 'orderinfo.classessetinfo', 'orderinfo.paytypeinfo'])
            ->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $info->goodslist = OrderSalesGoods::where(['pid' => $info->order_id, 'cp_id' => $cp_id, 'is_del' => 1])->whereIn('id', explode(',', $info->gids))->get();
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 订单审核取消
     */
    public function doorderauditcancel(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderSalesRedflush::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->red_audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '订单已审核，不可重复操作']);
        }
        DB::beginTransaction();
        try {
            OrderSalesRedflush::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['red_audit_status' => 3, 'red_audit_at' => time()]);
            OrderSalesGoods::where(['pid' => $info->order_id, 'cp_id' => $cp_id, 'is_del' => 1])->whereIn('id', explode(',', $info->gids))
                ->update(['red_audit_status' => 3, 'red_audit_at' => time(), 'red_status' => 1]);//审核取消红冲状态需要恢复


            OrderCommissionLog::where(['pid' => $info->order_id, 'cp_id' => $cp_id, 'red_status' => 1])->whereIn('sub_id', explode(',', $info->gids))
                ->update(['red_audit_status' => 3, 'red_audit_at' => time(), 'red_status' => 1]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '取消成功']);
    }

    /**
     * 订单审核通过
     */
    public function doorderauditsuccess(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderSalesRedflush::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();


        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->red_audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '订单已审核，不可重复操作']);
        }

        $goodslist = OrderSalesGoods::where(['pid' => $info->order_id, 'is_del' => 1, 'red_status' => 2])->whereIn('id', explode(',', $info->gids))->get()->toArray();
        if (empty($goodslist)) {
            return response()->json(['code' => '001', 'msg' => '红冲的商品不存在或红冲的商品已经处于红冲']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);

        $ordersalesinfo = OrderSales::where(['id' => $info->order_id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        DB::beginTransaction();
        try {
            $time = time();
            OrderSalesRedflush::query()
                ->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])
                ->update([
                    'red_audit_status' => 2,
                    'red_audit_at' => $time
                ]);
            OrderSalesGoods::query()
                ->where(['pid' => $info->order_id, 'cp_id' => $cp_id, 'is_del' => 1])
                ->whereIn('id', explode(',', $info->gids))
                ->update([
                    'red_audit_status' => 2,
                    'red_audit_at' => $time
                ]);

            OrderCommissionLog::query()
                ->where(['pid' => $info->order_id, 'cp_id' => $cp_id, 'red_status' => 1])
                ->whereIn('sub_id', explode(',', $info->gids))
                ->update([
                    'red_audit_status' => 2,
                    'red_audit_at' => $time
                ]);

            $goods_stock_ids = array_column($goodslist, 'goods_stock_id');
            $stockList = (new GoodsStockList())->getGoodsStockByIds($cp_id, $goods_stock_ids);

            if (!empty($goodslist)) {
                foreach ($goodslist as $val) {
                    $goods = $stockList[$val['goods_stock_id']] ?? [];
                    $stock = $goods;
                    // 此处需要重新计算业绩
                    if ($goods['is_code_more'] == 2) {
                        $goods['total_netglod_weight'] = $goods['total_netglod_weight'] + $val['weight'];
                        $val['total_netglod_weight'] = $val['weight'];
                    } else {
                        // 非一码多货 总件重和总金重

                        $goods['total_piece_weight'] = $goods['total_piece_weight'] + ($goods['piece_weight'] * $val['count']);
                        $val['total_piece_weight'] = $goods['piece_weight'] * $val['count'];

                        $goods['total_netglod_weight'] = $goods['total_netglod_weight'] + ($goods['netglod_weight'] * $val['count']);
                        $val['total_netglod_weight'] = $goods['netglod_weight'] * $val['count'];

                    }
                    list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($stock, $val, $goods['is_gram']);

                    $stockData = [
                        'count' => DB::raw('count +' . $val['count']),
                        'sales_count' => DB::raw('sales_count -' . $val['count']),
                        'total_piece_weight' => $goods['total_piece_weight'] ?? 0,
                        'total_netglod_weight' => $goods['total_netglod_weight'] ?? 0,
                        'total_cost_fee' => $total_cost_fee,
                        'costglod_price' => $costglod_price,
                        'piececost_fee' => $piececost_fee
                    ];

                    GoodsStockList::query()
                        ->where(['cp_id' => $cp_id, 'id' => $val['goods_stock_id'], 'store_id' => $val['store_id']])
                        ->update($stockData);

                    $goodsinfo = json_decode($val['goodsinfo'], true);

                    $goodsinfo['total_netglod_weight'] = $val['total_netglod_weight'];
                    $goodsinfo['total_cost_fee'] = $val['total_cost_fee'];
                    $goodsinfo['costglod_price'] = $costglod_price;
                    $goodsinfo['piececost_fee'] = $piececost_fee;

                    Goods::goodsLog($request, 0, intval($val['store_id']), $goodsinfo, intval($val['count']), 92, $info->order_sn);

                }
            }

            //如果存在使用余额、积分转预存的金额，是否退款到账户余额
            //如果赠送积分，是否扣除积分，如积分已使用如何处理
            $meminfo = Member::where(['cp_id' => $cp_id, 'id' => $info->mem_id, 'is_del' => 1])->first();


            if ($ordersalesinfo->mem_id > 0 && $ordersalesinfo->issendpoints == 2 && $ordersalesinfo->order_points > 0) {

                $order_points = array_sum(array_column($goodslist, 'order_points'));
                if (($meminfo->points_current - $order_points) < 0) {
                    $order_points = $meminfo->points_current;
                }

                $data = [
                    'cp_id' => $cp_id,
                    'mem_id' => $ordersalesinfo->mem_id,
                    'type' => 23,
                    'store_id' => $ordersalesinfo->store_id,
                    'change_val' => $order_points,
                    'change_before' => $meminfo->points_current,
                    'change_after' => $meminfo->points_current - $order_points,
                    'sales_account_id' => $info->shopping_account_id1,
                    'loginfo' => json_encode(['title' => '红冲扣除积分']),
                    'create_account_id' => $accountinfo['id'],
                    'update_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'update_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                    'update_at' => time(),
                    'remark' => '红冲扣除积分',
                ];
                MemberPointsChangelog::create($data);

                if ($meminfo->points_current > 0) {

                    $points = $meminfo->points_current - $order_points;
                    $points = $points > 0 ? $points : 0;
                    $points_total = $meminfo->points_total - $order_points;

                    $points_total = $points_total > 0 ? $points_total : 0;
                   // $shopping_times = $meminfo->shopping_times > 0 ? ($meminfo->shopping_times - 1) : 0;
                    Member::query()->where(['id' => $meminfo->id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'points_total' => $points_total,
                        'points_current' => $points,
                        //'shopping_times' => $shopping_times,
                    ]);
                    CommonMember::checkMemLv($meminfo->id);//会员升级
                }

            }

            if ($ordersalesinfo->mem_id > 0 && ($ordersalesinfo->balance_money > 0 || $ordersalesinfo->pointstobalance > 0)) {
                $balance_money = empty($goodslist) ? 0 : array_sum(array_column($goodslist, 'sub_balance_money'));
                $pointstobalance = empty($goodslist) ? 0 : array_sum(array_column($goodslist, 'sub_pointstobalance'));
                $data = [
                    'cp_id' => $cp_id,
                    'mem_id' => $ordersalesinfo->mem_id,
                    'type' => 99,
                    'store_id' => $ordersalesinfo->store_id,
                    'change_val' => $balance_money,
                    'change_before' => $meminfo->pre_money,
                    'change_after' => $meminfo->pre_money + $balance_money,
                    'sales_account_id' => $info->shopping_account_id1,
                    'loginfo' => json_encode(['title' => '红冲返回余额']),
                    'create_account_id' => $info->create_account_id,
                    'update_account_id' => $info->update_account_id,
                    'create_account_real_name' => $info->create_account_real_name,
                    'update_account_real_name' => $info->update_account_real_name,
                    'create_at' => time(),
                    'update_at' => time(),
                    'remark' => '红冲返回余额',
                ];

                MemberBalanceChangelog::create($data);
                Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                    'pre_money' => DB::raw('pre_money + ' . $balance_money),
                    'pointstobalance' => DB::raw('pointstobalance + ' . $pointstobalance)
                ]);
            }


            //收支流水
            $info['pay_type_id'] = $ordersalesinfo->pay_type_id ?? 0;
            $info['mixed_payment'] = $ordersalesinfo->mixed_payment ?? [];
            Financial::createMoneyLogByAuditCancel($cp_id, $info, $info->real_money, -1);


            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '审核成功']);
    }

    /**
     * 红冲导出
     */
    public function doexport(Request $request)
    {
        $list = OrderSalesRedflush::getList($request)['list'];
        $exceldata = [];
        $row = [
            ['table_header' => '红冲列表'],
            [
                'order_sn' => '订单号',
                'order_at' => '下单时间',
                'pay_status' => '支付状态',
                'shopping_account_info1' => '导购',
                'shopping_account_info2' => '副导购',
                'audit_status' => '审核状态',
                'red_audit_status' => '红冲审核',
                'goods_total_money' => '商品应收',
                'dold_fee_total' => '折旧费',
                'changegoods_money' => '换货金额',
                'coupon_money' => '抵用券金额',
                'total_money' => '订单应收',
                'real_money' => '订单实收',
                'order_discount' => '总折扣',
                'order_points' => '积分',
                'real_name' => '会员名称',
                'mobile' => '会员电话',
                'remark' => '备注',
                'create_account_real_name' => '创建人',
                'create_at' => '创建时间',
                'update_account_real_name' => '更新人',
                'update_at' => '更新时间',
                'add_fee' => '附加费',
                'truncate_glod_weight' => '截金重量',
                'truncate_glod_money' => '截金金额',
            ]
        ];
        foreach ($list as $val) {
            $exceldata[] = [
                'order_sn' => $val['orderinfo']['order_sn'],
                'order_at' => date('Y-m-d H:i:s', $val['orderinfo']['order_at']),
                'pay_status' => '已支付',
                'shopping_account_info1' => $val['shoppingaccountinfo1']['real_name'],
                'shopping_account_info2' => $val['shoppingaccountinfo2'] ? $val['shoppingaccountinfo2']['real_name'] : '',
                'audit_status' => '已审核',
                'red_audit_status' => $val['red_audit_status'] == 1 ? '待审核' : ($val['red_audit_status'] == 2 ? '审核' : '取消'),
                'goods_total_money' => $val['goods_total_money'] / 100,
                'dold_fee_total' => $val['dold_fee_total'] / 100,
                'changegoods_money' => 0,
                'coupon_money' => $val['coupon_money'] / 100,
                'total_money' => $val['total_money'] / 100,
                'real_money' => $val['real_money'] / 100,
                'order_discount' => $val['order_discount'] > 0 ? $val['order_discount'] : '无折扣',
                'order_points' => $val['order_points'],
                'mobile' => $val['memberinfo'] ? $val['memberinfo']['mobile'] : '',
                'real_name' => $val['memberinfo'] ? $val['memberinfo']['real_name'] : '',
                'remark' => $val['remark'],
                'create_account_real_name' => $val['create_account_real_name'],
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                'update_account_real_name' => $val['update_account_real_name'],
                'update_at' => date('Y-m-d H:i:s', $val['update_at']),
                'add_fee' => $val['add_fee'] / 100,
                'truncate_glod_weight' => $val['truncate_glod_weight'],
                'truncate_glod_money' => $val['truncate_glod_money'] / 100,
            ];
        }
        $filename = '红冲订单导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

}
